import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
// import { getToken } from '@/utils/auth'
import router from '@/router'
// create an axios instance
const request = axios.create({
  // baseURL: 'http://127.0.0.1:3000/api', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  baseURL: process.env.VUE_APP_URL,

  timeout: 5000 // request timeout
})

request.interceptors.request.use(
  (config) => {
    config.headers.Authorization = `Bearer ${store.state.user.token}`
    return config
  },
  (err) => {
    return Promise.reject(err)
  }
)
request.interceptors.response.use(
  (config) => {
    if (config.data.success) {
      return config.data
    } else {
      Message.error(config.data.message)
      // return undefined
      // 中止接口调用时.then的执行,直接执行.catch
      return Promise.reject(new Error(config.data.message))
    }
  },
  (err) => {
    if (err.response && err.response.status === 401) {
      store.commit('user/logout')
      Message.error(err.response.data.message)
      router.push('/login')
    }
    return Promise.reject(err)
  }
)
export default request
